package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {


    @Autowired
    MongoTemplate mongoTemplate;

    /**关键词联想功能实现
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAssociate(UserSearchDTO dto) {

        //参数检查
        if(StringUtils.isBlank(dto.getSearchWords())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据搜索的关键词进行模糊查询
        List<ApAssociateWords> wordsList = mongoTemplate
                //根据associateWords 进行模糊查询
                .find(Query.query(Criteria.where("associateWords")
                        //模糊查询语法
                .regex(".*" + dto.getSearchWords() + ".*")), ApAssociateWords.class);


        //返回结果
        return ResponseResult.okResult(wordsList);
    }
}
